<template>
  <div>
    科室界面
    <el-button type="primary" plain @click="addButtonClicked">添加</el-button>
    <el-button type="primary" plain @click="batchRemoveButtonClicked">批量删除</el-button>
    <el-button type="primary" plain @click="queryButtonClicked">查询</el-button>
    <el-button type="primary" plain @click="queryResetButtonClicked">重置</el-button>
    <el-table :data="deptData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column>
        <!-- <el-checkbox></el-checkbox> -->
        <el-table-column type="selection" width="55"></el-table-column>
      </el-table-column>
      <!-- <el-table-column prop="date" label="日期" width="180"></el-table-column> -->
      <el-table-column prop="deptName" label="科室名字" width="180"></el-table-column>
      <el-table-column prop="deptCode" label="科室编码" width="180"></el-table-column>
      <el-table-column prop="deptCategory" label="科室分类" width="180"></el-table-column>
      <!-- 其实在el-table下,书写的各个列的信息,然后会根据userData自动生成n行 -->
      <el-table-column align="right">
        <template slot-scope="scope">
          <el-button size="midium" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="midium" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加和修改 -->
    <el-dialog title="添加科室" :visible.sync="addDialogVisible">
      <el-form :model="department" ref="form" label-width="100px">
        <el-form-item label="名字" prop="name">
          <el-input v-model="department.deptName"></el-input>
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="department.deptCode"></el-input>
        </el-form-item>
        <!-- 主要是options的绑定 -->
        <el-form-item label="分类" prop="type">
          <el-select v-model="tmpDeptType" placeholder="请选择科室类型">
            <el-option
              v-for="item in deptTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 筛选界面 -->
    <el-dialog title="筛选科室" :visible.sync="queryDialogVisible">
      <el-form :model="departmentQuery" ref="form" label-width="100px">
        <el-form-item label="名字" prop="name">
          <el-input v-model="departmentQuery.deptName"></el-input>
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="departmentQuery.deptCode"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="type">
          <el-select v-model="tmpQueryDeptType" placeholder="请选择科室类型">
            <el-option
              v-for="item in deptTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="queryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="queryConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <div class="block">
      <span class="demonstration">显示总数</span>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPageNum"
        :page-sizes="[1, 5, 10]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRecord"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import {
  insert,
  update,
  deleteElem,
  getPage,
  getAll,
  getAllType
} from "@/api/department.js";
export default {
  mounted() {
    // 渲染完成
    this.loadPageData();
    this.loadType();
  },
  data() {
    return {
      // 复选框
      multipleSelection: [],
      // 分页
      pageSize: 5,
      totalRecord: 3,
      currentPageNum: 1,
      // 对话框
      addDialogVisible: false,
      queryDialogVisible: false,
      // 局部对象
      // 存储路径
      tmpDeptType: "",
      tmpQueryDeptType: "",
      department: {
        id: "",
        deptName: "",
        deptCode: "",
        deptCategory: "",
        deptType: ""
      },
      departmentQuery: {
        id: "",
        deptName: "",
        deptCode: "",
        deptCategory: "",
        deptType: ""
      },
      // 对象数组
      deptData: [
        // {
        //   id: "1",
        //   deptName: "急诊科",
        //   deptCode: "jzk",
        //   deptCategory: "资料"
        // },
        // {
        //   id: "2",
        //   deptName: "急诊科2",
        //   deptCode: "jzk2",
        //   deptCategory: "资料2"
        // },
        // {
        //   id: "3",
        //   deptName: "急诊科3",
        //   deptCode: "jzk3",
        //   deptCategory: "资料3"
        // }
      ],
      // 科室分类
      deptCategorys: [],
      // 科室类型
      deptTypes: []
    };
  },
  methods: {
    addButtonClicked() {
      // 清空
      this.department.id = "";
      this.department.deptName = "";
      this.department.deptCode = "";
      this.department.deptCategory = "";
      this.tmpDeptType = "";
      this.updateFlag = false;
      this.addDialogVisible = true;
      this.loadPageData();
    },
    loadType() {
      /*读取后端类别信息  */
      console.log("send getAlltype");
      getAllType().then(response => {
        /* todo: 重点是这里要改 */
        console.log("getType response,", response.data.data);
        if (response.data.code == 0) {
          /*todo: 处理 */
          this.deptTypes = [];
          for (var i = 0; i < response.data.data.length; i++) {
            let tmptype = {
              value: response.data.data[i].deptCategory,
              label: response.data.data[i].deptCategory
            };
            // let children = [];
            // for (
            //   var j = 0;
            //   j < response.data.data[i].departmentList.length;
            //   j++
            // ) {
            //   children.push({
            //     value: response.data.data[i].departmentList[j].deptName,
            //     label: response.data.data[i].departmentList[j].deptName
            //   });
            // }
            // if (children.length != 0) {
            //   tmptype.children = children;
            // }
            this.deptTypes.push(tmptype);
          }
          console.log("final Type message: ", this.deptTypes);
        } else {
          this.$message.error("读取类型信息失败");
        }
      });
      // this.deptTypes = [
      //   {
      //     value: "临床",
      //     label: "临床",
      //     children: [
      //       { value: "内科", label: "内科" },
      //       { value: "外科", label: "外科" },
      //       { value: "骨科", label: "骨科" }
      //     ]
      //   },
      //   { value: "医技", label: "医技" },
      //   { value: "财务", label: "财务" },
      //   { value: "行政", label: "行政" },
      //   { value: "其他", label: "其他" }
      // ];
    },
    loadPageData() {
      // 这个函数会更新总个数和数组中的信息
      console.log("initPageData");
      // 查询条件
      let pageParam = {
        deptCode: this.departmentQuery.deptCode,
        deptName: this.departmentQuery.deptName,
        deptCategory: this.tmpQueryDeptType,
        /* 将deptType设置为空 */
        deptType: "",
        curPage: this.currentPageNum,
        pageSize: this.pageSize
      };
      console.log("send getPage Params: ", pageParam);
      getPage(pageParam).then(response => {
        console.log(" getPage response: ", response);
        if (response.data.code == 0) {
          this.currentPageNum = parseInt(response.data.data.current);
          this.deptData = response.data.data.records;
          this.totalRecord = parseInt(response.data.data.total);
          console.log("getPage: ", this.deptData);
        } else {
          console.log("getPage ERROR!!");
        }
      });
    },
    save() {
      console.log("save");
      this.addDialogVisible = false;
      /* 将deptType设置为空 */
      this.department.deptType = "";
      this.department.deptCategory = this.tmpDeptType;
      if (this.updateFlag) {
        console.log("for 修改");
        /* update */
        let updateParam = {
          deptCategory: this.department.deptCategory,
          deptCode: this.department.deptCode,
          deptName: this.department.deptName,
          deptType: this.department.deptType,
          id: parseInt(this.department.id)
        };
        console.log("send update:", updateParam);
        update(updateParam).then(response => {
          if (response.data.code == 0) {
            this.$message("修改成功");
            this.loadPageData();
          } else {
            this.$message.error("修改成功");
          }
        });
      } else {
        console.log("for 新增");
        /* insert */
        let insertParams = {
          deptCategory: this.department.deptCategory,
          deptCode: this.department.deptCode,
          deptName: this.department.deptName,
          deptType: this.department.deptType
        };
        console.log("send insert:", insertParams);
        insert(insertParams).then(response => {
          if (response.data.code == 0) {
            this.$message("添加成功");
            this.loadPageData();
          } else {
            this.$message.error("添加失败,科室已存在");
          }
        });
      }
    },
    handleEdit(index, row) {
      this.dialogTitle = "修改";
      this.addDialogVisible = true;
      // 切记此处不可直接赋值,直接赋值的话传递的是引用,先修改再新建的话,就会影响到之前被修改的行
      this.department = JSON.parse(JSON.stringify(row));
      this.updateFlag = true;
    },
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除此项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          /*todo: 在这里填写在数据库中删除的语句 */
          let deleteParam = { ids: [row.id] };
          console.log("send deleteElem:", deleteParam);
          deleteElem(deleteParam).then(response => {
            if (response.data.code == 0) {
              this.$message("删除成功");
              this.loadPageData();
            } else {
              this.$message.error("删除失败");
            }
          });
          console.log("handleDelete: remove", row.deptName);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      // 更新页数
      this.loadPageData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPageNum = val;
      // 更新页数
      this.loadPageData();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(val);
    },
    batchRemoveButtonClicked() {
      this.$confirm("此操作将永久删除选中项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          /* 先封装成数组,再删除 */
          let removeIds = [];
          this.multipleSelection.forEach(item => {
            removeIds.push(item.id);
          });
          let deleteParam = {
            ids: removeIds
          };
          console.log("send deleteElem:", deleteParam);
          deleteElem(deleteParam).then(response => {
            if (response.data.code == 0) {
              this.$message("删除成功");
              this.loadPageData();
            } else {
              var failedids = "[";
              response.data.data.ids.forEach(item => {
                failedids += item + ",";
              });
              failedids += "]";
              response.data.data.ids;
              this.$message.error("删除 " + failedids + " 失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    queryButtonClicked() {
      this.queryDialogVisible = true;
    },
    queryConfirm() {
      this.queryDialogVisible = false;
      this.currentPageNum = 1;
      this.loadPageData();
    },
    queryResetButtonClicked() {
      this.departmentQuery.id = "";
      this.departmentQuery.deptName = "";
      this.departmentQuery.deptCode = "";
      this.departmentQuery.deptCategory = "";
      this.departmentQuery.deptType = "";
      this.tmpQueryDeptType = "";
      this.loadPageData();
    },
    handleChange(value) {
      /* 返回的是字符串数组,就是你逐层的选择,数组的长度就是选择的深度 */
      console.log(value);
    }
  }
};
</script>

<style>
</style>